import { FC } from 'react';
import styles from './index.module.scss';
import useGetComponentInfo from '../../../../../hooks/useGetComponentInfo';
import classNames from 'classnames';
import { ComponentInfoType } from '../../../../../store/componentReducer';
import { getComponentConfigByType } from '../../../../../components/QuestionComponents';

type PropsType = {
  selectedComponentId: string;
  setSelectedComponentId: (id: string) => void;
  setSelectedComponentType: (type: string) => void;
};
const LeftPanel: FC<PropsType> = (props: PropsType) => {
  const { selectedComponentId, setSelectedComponentId, setSelectedComponentType } = props;
  const { componentList } = useGetComponentInfo();
  function handleClick(id: string, type: string) {
    setSelectedComponentId(id);
    setSelectedComponentType(type);
  }
  function genComponent(componentInfo: ComponentInfoType) {
    const { type, props } = componentInfo;
    const componentConfig = getComponentConfigByType(type);
    console.log('componentConfig', componentConfig);
    if (!componentConfig) return;
    const { Component } = componentConfig;
    return <Component {...props} />;
  }

  return (
    <div className={styles.container}>
      {componentList
        .filter((c) => !c.isHidden)
        .map((c) => {
          const { fe_id, type } = c;
          const wrapperDefaultClassName = styles['component-wrapper'];
          const selectedClassName = styles.selected;
          const wrapperClassName = classNames({
            [wrapperDefaultClassName]: true,
            [selectedClassName]: fe_id === selectedComponentId,
          });
          return (
            <div key={fe_id} className={wrapperClassName} onClick={() => handleClick(fe_id, type)}>
              <div className={styles.component}>{genComponent(c)}</div>
            </div>
          );
        })}
    </div>
  );
};

export default LeftPanel;
